package com.yxw.blog.conf.requestprocessor;

import com.yxw.blog.annotation.UnInterception;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * 自定义拦截器
 * @author yexinwei
 * @date 2021/4/29
 */
@Component
public class AccessControllerInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //如果不是映射到方法上，则直接放行
        if(!(handler instanceof  HandlerMethod)){
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod)handler;
        //获取控制层的方法
        Method method = handlerMethod.getMethod();
        //获取方法的名字（测试）
        String methodName = method.getName();
        //获取方法上的注解，判断是否拦截,如果有注解，则直接放行，否则进一步判断
        UnInterception unInterception = method.getAnnotation(UnInterception.class);
        if(unInterception!=null){
            return true;
        }else{
            //根据请求获取session
            HttpSession session = request.getSession();
            //根据session获取userId
            Integer userId = (Integer)session.getAttribute("userId");
            //如果userId不为空，说明已经登录，放行，否则拦截
            if(userId!=null){
                return true;
            }else{
                System.out.println("拦截:"+methodName);
                return false;
            }
        }
    }
}
